package com.gxpt.app.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bigkoo.convenientbanner.CBViewHolderCreator;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseFragment;
import com.gxpt.app.Constant;
import com.gxpt.app.R;
import com.gxpt.app.adapter.hotgoods_Adapter;
import com.gxpt.app.bean.getcarousel_bean;
import com.gxpt.app.bean.hotgoods_bean;
import com.gxpt.app.codes.NetworkImageHolderView;
import com.gxpt.app.view.Activity_city_select_2;
import com.gxpt.app.view.Activity_life_need_add;
import com.gxpt.app.view.Activity_mall_types;
import com.gxpt.app.view.Activity_webview;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/9/8.
 */

@ContentView(R.layout.fragment_mall)
public class Fragment_mall extends BaseFragment {

    Context context;
    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private hotgoods_Adapter mDataAdapter = null;

    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;


    @ViewInject(R.id.toMORE)
    ImageView toMORE;

    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;





    private View topView;

    private ConvenientBanner convenientBanner;//顶部广告栏控件
    private ArrayList<Integer> localImages = new ArrayList<Integer>();
    private List<String> networkImages;
    private String[] images = {"http://www.jikew.cn/uploads/image/focus/2017/0328/20170328155439_28832.jpg#####999#####0"};

    int pic_hight;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden == false){
            AppUtils.isShowAreaSel(context);
        }
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = x.view().inject(this, inflater, container);
        initViews(rootView);
//        initData();
        return  rootView;
    }

    private void initViews(View rootView) {
        try {
            pic_hight = ScreenUtils.getScreenWidth(context) / 16 * 10;//16:9高
        } catch (Exception e) {
            pic_hight = 600;
        }

        initBars();
        ///////////////////////////////////////////
        mDataAdapter = new hotgoods_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
        mLRecyclerViewAdapter.addHeaderView(topView);
        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mLRecyclerView.setLoadMoreEnabled(false);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
//                do_LoadMore();
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    hotgoods_bean.hotgoods item = mDataAdapter.getDataList().get(position);
                    Bundle b = new Bundle();
                    b.putString("ID",item.id);
                    Intent gonew =new Intent();
                    gonew.setClass(context,Activity_webview.class);
                    gonew.putExtra("DATA",b);
                    startActivity(gonew);

                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }

    private void do_Refresh(){
        page_num = 1;
        toNet_getcarousel();//轮播图
        toNet_hotgoods();//最新
    }

    private void do_LoadMore(){
//        page_num += 1;
//        toNet_hotgoods();//最新
    }
    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<hotgoods_bean.hotgoods> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }


    private void initBars(){
        topView = LayoutInflater.from(context).inflate(R.layout.item_mall_area,null, false);
        topView.setLayoutParams(new LRecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));

        convenientBanner     = (ConvenientBanner)topView.findViewById(R.id.convenientBanner);


        networkImages= Arrays.asList(images);
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        },networkImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})

                //设置翻页的效果，不需要翻页效果可用不设
                .setPageTransformer(ConvenientBanner.Transformer.DefaultTransformer)
                .setMinimumHeight(pic_hight);
    }

    private void initConvenientBanner_net_update(String[] pics){
        //headview
        networkImages= Arrays.asList(pics);
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {


            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }

        },networkImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                //设置翻页的效果，不需要翻页效果可用不设
                .setPageTransformer(ConvenientBanner.Transformer.DefaultTransformer);

        convenientBanner.startTurning(5000);
    }



    @Event(value={R.id.toMORE})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toMORE:
                Intent goNewView = new Intent();
                goNewView.setClass(context, Activity_mall_types.class);
                startActivity(goNewView);
                break;

        }
    }


    /////NET
    private void toNet_getcarousel(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shop");
            jsonBody.put("serviceName",          "getcarousel");

            jsonBody.put("type",                 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.http_post_string(Constant.URL_getcarousel,jsonBody.toString(),do_getcarousel);
    }

    private void toNet_hotgoods(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shop");
            jsonBody.put("serviceName",          "hotgoods");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i("toNet_hotgoods = "+jsonBody.toString());
        HttpUtils.http_post_string(Constant.URL_hotgoods,jsonBody.toString(),do_hotgoods);
    }

    //////NET DO
    StringCallback do_getcarousel = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
//            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
          Logger.e("do_getcarousel = "+s);
            try{
                getcarousel_bean data = new Gson().fromJson(s, getcarousel_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    String[] pics = new String[data.data.size()];
                    for(int a=0;a < data.data.size();a++){
                        pics[a] = data.data.get(a).url+"#####1#####"+data.data.get(a).link;
                    }

                    initConvenientBanner_net_update(pics);
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    StringCallback do_hotgoods = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e("do_hotgoods = "+s);
            try{
                hotgoods_bean data = new Gson().fromJson(s, hotgoods_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
//                    if(data.data != null){
//                        if(data.data.size()>0){
//                            init_List_data(data.data);
//                        }
//                    }

                    if(data.data != null){
                        if(data.data.size()>0){
                            addItems((ArrayList)data.data);
                            notifyDataSetChanged();
                        }else{
                            page_num -= 1;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
